const db = require('../../models/index');
const DAO = require('../../dao/sql-option-dao');
const Op = db.Op;
const logger = require('../../utils/logger-util');
const Roles = db.roles;
const Menus = db.menus;
const rolesMenus = db.rolesMenus;

// 角色-菜单 多对多关系
Roles.belongsToMany(Menus, { 
    through: {
        model: rolesMenus,
        // unique: false, //  uniqueKey 参数覆盖此唯一键名. 若不希望产生唯一键, 可以使用 unique: false 参数.
    },
    foreignKey: 'roleId',
    // foreignKey: 'role_id',
    // otherKey:'menus_id'
});

Menus.belongsToMany(Roles, { 
    through: {
        model: rolesMenus,
        // unique: false, //  uniqueKey 参数覆盖此唯一键名. 若不希望产生唯一键, 可以使用 unique: false 参数.
    },
    foreignKey: 'menuIds',
    // foreignKey: 'menu_ids',
    // otherKey:'role_id'
});

// 创建角色
exports.create = async (req, res) => {
    try {
        const roleInfo = req.body;
        const roles = {
            roleName: roleInfo.roleName,
            sort: roleInfo.sort,
            state: roleInfo.state,
            roleDesc: roleInfo.roleDesc,
            menuIds: roleInfo.menuIds
        };
        // 查找角色是否已经存在
        await Roles.findOne({ where: { roleName:roleInfo.roleName } })
        .then(roleData => {
            if(roleData && roleData.id) {
                res.sendResultAto(null, 605, '角色已存在');
                throw new Error();
            }
        });
        // 查询选中的菜单
        let menus = await Menus.findAll({ 
            where: { 
                id:roles.menuIds
            }
        });
        // 创建角色
        let newRole = await Roles.create(roles);
        // 更新中间表
        await newRole.setMenus(menus);
        res.sendResultAto(null, 200, '创建成功');
    } catch (e) {
        console.log(e);
        logger.error(e);
        res.sendResultAto(null, 500, '服务器错误');
    };
};

// 查询所有角色
exports.findAll = (req, res) => {
    const roleInfo = req.body;
    roleInfo.raw = false; //是否开启原生查询
    roleInfo.include = [ // 执行预先加载
        {
            model: Menus
        }
    ];
    DAO.list(Roles, roleInfo, list => {
        res.sendResult(list)
    });
};

// 根据角色id 查询角色信息
exports.findOne = async (req, res) => {
    const roleInfo = req.body;
    roleInfo.raw = false; //是否开启原生查询
    roleInfo.include = [ // 执行预先加载
        {
            model: Menus
        }
    ];
    DAO.findOne(Roles, roleInfo, data => {
        res.sendResultAto(data.data, 200, '查询成功')
    });
};

// 查询多个角色信息
exports.findRoles = (req, res) => {
    try {
        const roleInfo = req.body;
        Roles.findAll({
            where: {
                id: roleInfo.id
            },
            include: {
                model: Menus
            }
        }).then(data => {
            res.sendResultAto(data, 200, '查询成功');
        });
    } catch (error) {
        console.log(e);
        logger.error(e);
        res.sendResultAto(null, 500, '服务器错误');
    };
};

// 更新角色信息
exports.update = async (req, res) => {
    try {
        const roleInfo = req.body;
        // 查询选中的菜单
        let menus = await Menus.findAll({ where: { id: roleInfo.menuIds} }); 
        // findByPk方法通过主键返回表里一行数据
        Roles.findByPk(roleInfo.id).then(role => {
            role.update(roleInfo);
            role.setMenus(menus);
            res.sendResultAto(null, 200, '修改成功');
        });
    } catch (e) {
        console.log(e);
        logger.error(e);
        res.sendResultAto(null, 500, '服务器错误');
    };
};

// 删除角色信息
exports.delete = (req, res) => {
    try {
        const roleInfo = req.body;
        rolesMenus.destroy({ where: { roleId:roleInfo.id } })
        .then(dataMenu => {
            DAO.delete(Roles, {id:roleInfo.id}, data => {
                res.sendResult(data);
            });
        });
    } catch (e) {
        console.log(e);
        logger.error(e);
        res.sendResultAto(null, 500, '服务器错误');
    };
};

// 删除所有角色信息
exports.deleteAll = (req, res) => {
    DAO.deleteAll(Roles, data => {
        res.sendResult(data);
    });
};